/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { UseButton, UsePopup } from './types';
import { computed, nextTick, ref, Ref, SetupContext } from 'vue';
import { ButtonEditProps } from '../button-edit.props';
import OverylayService from '../../../overlay/src/overlay.service';

export function useButton(
    props: ButtonEditProps,
    context: SetupContext,
    buttonEditRef: Ref<any>,
    usePopupComposition: UsePopup
): UseButton {
    const buttonBehavior = ref(props.buttonBehavior);
    const shouldPopupOnInput = ref(props.popupOnInput);
    const buttonClass = computed(() => ({
        'input-group-append': true,
        'append-force-show': props.showButtonWhenDisabled && (props.readonly || props.disable)
    }));

    const canClickAppendButton = computed(() => props.showButtonWhenDisabled || ((!props.editable || !props.readonly) && !props.disable));

    async function onClickButton($event: Event) {
        if (canClickAppendButton.value) {
            const hasContent = !!context.slots.default;
            if (buttonBehavior.value === 'Overlay') {
                OverylayService.show({
                    host: buttonEditRef.value,
                    render: () => {
                        if (context.slots.default) {
                            return context.slots.default();
                        }
                    }
                });
            }
            if (hasContent && buttonBehavior.value === 'Popup') {
                usePopupComposition.togglePopup();
            }
            if (hasContent && shouldPopupOnInput.value) {
                usePopupComposition.hidePopup();
            }
            context.emit('clickButton', { origin: $event, value: props.modelValue });
        }
        $event.stopPropagation();
    }

    function onMouseEnterButton($event: MouseEvent) {
        context.emit('mouseEnterIcon', $event);
    }

    function onMouseLeaveButton($event: MouseEvent) {
        context.emit('mouseLeaveIcon', $event);
    }

    function onMouseOverButton() {
        context.emit('mouseOverButton');
    }

    return {
        buttonClass,
        onClickButton,
        onMouseEnterButton,
        onMouseLeaveButton,
        onMouseOverButton
    };
}
